<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="../vue.js" type="text/javascript" charset="utf-8"></script>
  <script src="./data.js"></script>
  <link rel="stylesheet" href="./index.css">
</head>

<body>
  <div id="app">
    <button @click="allChoose(10086)">全选</button>
    <button @click="allChoose(10010)">反选</button>
    <h1>总价：￥{{total}}元 </h1>

    <box ref="box" @calc="calcFn" v-for="(item,index) in goods" :item="item" :key="index"></box>
  </div>
</body>

<!-- 卡片组件 -->
<template id="box">
  <div class="box">
    <img class="cho" @click="swi = !swi" :src="choose" alt="">
    <img class="logo" :src="item.img" alt="">
    <h3>{{item.title}}</h3>
    <h5>价格：¥{{item.price}}</h5>

    <section>
      <button @click="item.number <= 1 ? item.number = 1 : item.number--">-</button>
      <input type="text" v-model.number="item.number">
      <button @click="item.number++">+</button>

    </section>
    <h1>组件总价：￥ {{ (item.price * item.number).toFixed(2) }} 元</h1>
  </div>
</template>

<script type="text/javascript">
  const app = Vue.createApp({
    data() {
      return {
        goods,
        total: 0
      }
    },
    methods: {
      // 用来计算总价格
      calcFn() {
        console.log('计算价格');

        if (!this.$refs.box) return

        // 找到所有商品，然后将被选中的商品价格相加
        let num = 0 // 计算总价格的
        for (let i = 0; i < this.$refs.box.length; i++) {
          // console.log(this.$refs.box[0]);
          const item = this.$refs.box[i].item
          if (this.$refs.box[i].swi) {
            // console.log(item, item.number);
            // 被选中了，需要计算价格
            num += item.price * item.number
          }
        }

        // 合计总价格
        this.total = num.toFixed(2)

      },
      allChoose(type) {
        // 处理全选和反选用的
        // console.log(this.$refs.box);
        for (let i = 0; i < this.$refs.box.length; i++) {
          if (type == 10086) {
            this.$refs.box[i].swi = true
          } else {
            this.$refs.box[i].swi = !this.$refs.box[i].swi
          }

        }
      }
    },
  })


  app.component('box', {
    template: '#box',
    props: ['item'],
    data() {
      return {
        // 用来标记当前组件是否被选中
        swi: false
      }
    },
    computed: {
      choose() {
        // console.log('11111');
        this.$emit('calc')
        // 通过计算属性监听 swi 来确定有没有被选中
        return this.swi ? 'choose2.png' : 'choose.png'
      }
    }
  })

  app.mount('#app')
</script>

</html>